#include "messageeditarea.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollBar>
#include <QPainter>
#include <QStyleOption>
#include <QFileDialog>
#include "debug.h"
#include "historymessagedialog.h"
#include "model/datacenter.h"
#include "toast.h"
#include "mainWidget.h"
#include "soundrecorder.h"

messageEditArea::messageEditArea(QWidget *parent)
    : QWidget{parent}
{
    //1.设置总体属性
    this->setFixedHeight(200/SCALE);
    this->setStyleSheet("border-top: 1px solid rgba(210,210,210,0.5);");

    //2.设置垂直水平布局管理器
    QVBoxLayout* VLayout = new QVBoxLayout;
    QHBoxLayout* HLayout = new QHBoxLayout;
    this->setLayout(VLayout);
    VLayout->addLayout(HLayout);

    HLayout->setAlignment(Qt::AlignTop|Qt::AlignLeft);
    HLayout->setSpacing(0);
    VLayout->setContentsMargins(15/SCALE,2,20/SCALE,10/SCALE);

    //3.设置发送不同类型消息的按钮
    sendImageBtn = new QPushButton;
    sendImageBtn->setIcon(QIcon(":/myResource/Image/image.svg"));
    sendImageBtn->setFixedSize(40/SCALE,40/SCALE);
    sendImageBtn->setIconSize(QSize(25/SCALE,25/SCALE));
    QString style ="QPushButton{border:none;background-color:rgb(245,245,245);}";
    style+="QPushButton:pressed{background-color:rgb(220,220,220);}";
    sendImageBtn->setStyleSheet(style);
    HLayout->addWidget(sendImageBtn);

    sendFileBtn = new QPushButton;
    sendFileBtn->setIcon(QIcon(":/myResource/Image/file.svg"));
    sendFileBtn->setFixedSize(40/SCALE,40/SCALE);
    sendFileBtn->setIconSize(QSize(25/SCALE,25/SCALE));
    sendFileBtn->setStyleSheet(style);
    HLayout->addWidget(sendFileBtn);

    sendSpeechBtn = new QPushButton;
    sendSpeechBtn->setIcon(QIcon(":/myResource/Image/speech2.svg"));
    sendSpeechBtn->setFixedSize(40/SCALE,40/SCALE);
    sendSpeechBtn->setIconSize(QSize(25/SCALE,25/SCALE));
    sendSpeechBtn->setStyleSheet(style);
    HLayout->addWidget(sendSpeechBtn);

    showHistoryBtn = new QPushButton;
    showHistoryBtn->setIcon(QIcon(":/myResource/Image/history.svg"));
    showHistoryBtn->setFixedSize(40/SCALE,40/SCALE);
    showHistoryBtn->setIconSize(QSize(25/SCALE,25/SCALE));
    showHistoryBtn->setStyleSheet(style);
    HLayout->addWidget(showHistoryBtn);

    //4.添加多行编辑框

    textEidt = new QPlainTextEdit;
    textEidt->setStyleSheet("QPlainTextEdit{border:none;font-size:14px;}");
    textEidt->verticalScrollBar()->setStyleSheet("QScrollBar:vertical{width:2px;background-color:rgb(216,216,216);}");
    VLayout->addWidget(textEidt);

    //5.设置提示标签
    tipLabel = new QLabel;
    tipLabel->setText("录音中...");
    tipLabel->setFont(QFont("微软雅黑",24,600));
    VLayout->addWidget(tipLabel);
    tipLabel->hide();

    //6.设置提交按钮
    sendTextBtn = new QPushButton;
    sendTextBtn->setText("发送");
    sendTextBtn->setFixedSize(120/SCALE,40/SCALE);
    QString style2 = "QPushButton { font-size: 16px; color: rgb(7, 193, 96); border: none; background-color: rgb(233, 233, 233); border-radius: 10px; } ";
    style2 += "QPushButton:hover { background-color: rgb(210, 210, 210); }";
    style2 += "QPushButton:pressed { background-color: rgb(190, 190, 190); }";
    sendTextBtn->setStyleSheet(style2);
    VLayout->addWidget(sendTextBtn,0, Qt::AlignRight | Qt::AlignVCenter);

    //7.初始化信号和槽
    initSignalSlot();

}
void messageEditArea::paintEvent(QPaintEvent* event)
{
    (void) event;
    QStyleOption opt;
    opt.initFrom(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}
void messageEditArea::initSignalSlot()
{
    model::DataCenter* datacenter = model::DataCenter::getInstance();
    connect(showHistoryBtn,&QPushButton::clicked,this,[=]
    {
        if(datacenter->getCurrentSessionId().isEmpty())
        {
            Toast::showMessage("当前未选中会话，无法查看历史消息");
            return;
        }
        HistoryMessageDialog* historyMessageDialog = new HistoryMessageDialog(this);
        historyMessageDialog->exec();
    });
    connect(sendTextBtn,&QPushButton::clicked,this,&messageEditArea::sendTextMessage);
    connect(datacenter,&model::DataCenter::sendMessageDone,this,&messageEditArea::addMyselfMessage);
    connect(datacenter,&model::DataCenter::receiveMessageDone,this,&messageEditArea::addOtherMessage);
    connect(sendImageBtn,&QPushButton::clicked,this,&messageEditArea::sendImageMessage);
    connect(sendFileBtn,&QPushButton::clicked,this,&messageEditArea::sendFileMessage);

    connect(sendSpeechBtn,&QPushButton::pressed,this,&messageEditArea::pressSpeechMessage);
    connect(sendSpeechBtn,&QPushButton::released,this,&messageEditArea::releaseSpeechMessage);
    SoundRecorder* soundRecorder = SoundRecorder::getInstance();
    connect(soundRecorder,&SoundRecorder::soundRecordDone,this,&messageEditArea::sendSpeechMessage);
}

void messageEditArea::sendTextMessage()
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    //1.未选中会话，或者输入框是空的就不发送信息
    if(dataCenter->getCurrentSessionId().isEmpty())
    {
        LOG()<<"当前未选中任何会话，无法发送消息";
        Toast::showMessage("未选中任何会话，不发送消息");
        return;
    }
    if(textEidt->toPlainText().trimmed().isEmpty())
    {
        LOG()<<"输入框为空";
        return;
    }
    //2.清空输入框数据，并网络发送数据给服务器
    QString cont = textEidt->toPlainText();
    textEidt->setPlainText("");
    LOG()<<"要向网络发送的文本消息为:"<<cont<<",要向SessionId:"<<dataCenter->getCurrentSessionId()<<"发送";
    dataCenter->sendTextMessageAsync(dataCenter->getCurrentSessionId(),cont);
}

void messageEditArea::sendImageMessage()
{
    //1.确保选中存在的会话后才能发送信息
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    if(dataCenter->getCurrentSessionId().isEmpty())
    {
        Toast::showMessage("当前未选中任何会话，无法发送消息");
        return;
    }
    //2.使用弹窗获取文件
    QString filter ="Image File(*.png *.jpg *.svg *.jpeg)";
    QString ImagePath = QFileDialog::getOpenFileName(this,"选择图片",QDir::homePath(),filter);
    if(ImagePath.isEmpty())
    {
        LOG()<<"用户取消了选择图片文件";
        return;
    }
    //3.读取照片内容
    QByteArray content = model::loadFileToByteArray(ImagePath);
    //4.发送请求
    dataCenter->sendImageMessageAsync(dataCenter->getCurrentSessionId(),content);
}

void messageEditArea::sendFileMessage()
{
    //1.确保选中存在的会话后才能发送信息
    model::DataCenter* dataCenter = model::DataCenter::getInstance();
    if(dataCenter->getCurrentSessionId().isEmpty())
    {
        Toast::showMessage("当前未选中任何会话，无法发送消息");
        return;
    }
    //2.使用弹窗获取文件
    QString FilePath = QFileDialog::getOpenFileName(this,"选择文件",QDir::homePath(),"*");
    if(FilePath.isEmpty())
    {
        LOG()<<"用户取消了选择文件文件";
        return;
    }
    //3.读取照片内容
    QByteArray content = model::loadFileToByteArray(FilePath);
    QFileInfo fileInfo(FilePath);
    //4.发送请求
    dataCenter->sendFileMessageAsync(dataCenter->getCurrentSessionId(),content,fileInfo.fileName());
}

void messageEditArea::pressSpeechMessage()
{
    model::DataCenter* dataCenter=model::DataCenter::getInstance();
    if(dataCenter->getCurrentSessionId().isEmpty())
    {
        Toast::showMessage("当前未选中任何会话，无法发送消息");
        return;
    }
    sendSpeechBtn->setIcon(QIcon(":/myResource/Image/activeSpeech.svg"));
    SoundRecorder* speechRecorder =SoundRecorder::getInstance();
    speechRecorder->startRecord();
    tipLabel->show();
    textEidt->hide();
}

void messageEditArea::releaseSpeechMessage()
{
    model::DataCenter* dataCenter=model::DataCenter::getInstance();
    sendSpeechBtn->setIcon(QIcon(":/myResource/Image/speech2.svg"));
    SoundRecorder* speechRecorder =SoundRecorder::getInstance();
    speechRecorder->stopRecord();
    textEidt->show();
    tipLabel->hide();
}

void messageEditArea::sendSpeechMessage(const QString& path)
{
    const QByteArray& content = model::loadFileToByteArray(path);
    model::DataCenter* dataCenter =model::DataCenter::getInstance();
    dataCenter->sendSpeechMessageAsync(dataCenter->getCurrentSessionId(),content);
}


void messageEditArea::addMyselfMessage(model::MessageType type, const QByteArray &content, const QString &extraInfo)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    //1.构建消息
    model::Message msg = model::Message::makeMessage(type,dataCenter->getCurrentSessionId()
                                                     ,*dataCenter->getMyself(),content,extraInfo);
    //2.对内存的数据进行更新
    dataCenter->addMessage(msg);
    //3.展示到消息展示区
    messageShowArea* MShowArea = MainWidget::getInstance()->getMessageShowArea();
    MShowArea->addMessage(false,msg);
    //4.拉滚动条
    MShowArea->scrollToEnd();
    //5.发送信号更新最后一条信息在页面上的展示
    emit dataCenter->updateLastMessage(dataCenter->getCurrentSessionId());
}

void messageEditArea::addOtherMessage(const model::Message &msg)
{
    model::DataCenter* dataCenter = model::DataCenter::getInstance();

    //3.展示到消息展示区
    messageShowArea* MShowArea = MainWidget::getInstance()->getMessageShowArea();
    MShowArea->addMessage(true,msg);
    //4.拉滚动条
    MShowArea->scrollToEnd();
}


